import {getToken, removeToken, setToken} from "@/utils/auth";
import {getInfo, login} from "../../http/api/login";

const user = {
    state:{
        token: getToken(),
        roles:[],
        name:'',
        avatar:'',
        userInfo:{}
    },
    mutations:{
        SET_TOKEN(state, token){
            state.token = token
        },
        REMOVE_TOKEN(state){
            state.token = ""
        },
        SET_NAME(state,name){
            state.name = name
        },
        SET_AVATAR(state,avatar){
            state.avatar  = avatar
        },
        SET_ROLES(state,roles){
            state.roles = roles
        },
        REMOVE_ROLES(state){
            state.roles = []
        },
        SET_USER_INFO(state,userInfo){
            state.userInfo = userInfo
        }
    },
    actions:{
        //登录
        login({commit},userInfo){
            const username = userInfo.username.trim();
            const password = userInfo.password;
            return new Promise((resolve, reject) => {
                login(username,password).then(res=>{
                    if (res.status === 200){
                        setToken(res.data)
                        commit('SET_TOKEN',res.data)
                        resolve()
                    }
                    resolve()
                }).catch(error=>{
                    reject(error)
                })
            })
        },
        //登出
        logout({commit}){
            removeToken()
            commit('REMOVE_TOKEN')
            commit('REMOVE_ROLES')
        },
        // 获取用户信息
        getUserInfo({commit}){
            return new Promise((resolve, reject) => {
                getInfo().then(res=>{
                    commit('SET_NAME',res.data.name)
                    commit('SET_AVATAR',res.data.avatar)
                    commit('SET_ROLES',['DEFAULT_ROLE'])
                    commit('SET_USER_INFO',res.data)
                    resolve()
                }).catch(error=>{
                    reject(error)
                })
            })
        }
    }
}

export default user;
